//
//  HJCityListVC.m
//  project
//
//  Created by jc on 2019/4/12.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJCityListVC.h"
#import "HJCityCell.h"

@interface HJCityListVC ()<UICollectionViewDelegate, UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIView *collectionBG;
@property (weak, nonatomic) IBOutlet UIView *tableBG;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableViewBGConstraintBottom;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *top;
@property (nonatomic,strong) UICollectionView * collectionView;
@property (nonatomic,strong) UITableView * tableView;
@property (nonatomic,strong) NSMutableArray * dataArray;
@property (nonatomic,strong) NSDictionary * dict;
@property (nonatomic,strong) NSMutableArray * hotArray;
@property (nonatomic,assign) BOOL headerTitleAdd;
@end
static NSString * const identifier = @"CityCell";
static NSString * const Headridentifier = @"Headridentifier";
static NSInteger count = 1;

@implementation HJCityListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navTitle = @"选择城市";
    self.top.constant = 4;
    [self.collectionBG rounded:(UIRectCornerAllCorners) radius:10];
//    [self.tableBG rounded:(UIRectCornerTopRight | UIRectCornerBottomRight) radius:10];
    
    [self loadHotCity];
}

-(NSMutableArray *)hotArray {
    if (!_hotArray) {
        _hotArray = [NSMutableArray array];
    }
    return _hotArray;
}

-(void)loadHotCity {
    WS(weakSelf)
    [[HJCityManager manager] cityDataSourceWithHeadTitles:^(NSArray * _Nonnull titles, NSDictionary * _Nonnull dic) {
        weakSelf.dict = dic;
        weakSelf.dataArray = [NSMutableArray arrayWithArray:titles];
        [weakSelf.tableView reloadData];
        
        // 更新 TableView 的 frame
        CGFloat height = 20 * weakSelf.dataArray.count;
        CGFloat width = 30;
        
        CGFloat Y =  ((SCREEN_HEIGTH - Height_NavBar - 5 - (IS_FULL_SCREEN ? 34 : 12)) - height) / 2;
        CGFloat X = CGRectGetMaxX(self.collectionView.frame);
        weakSelf.tableView.frame = CGRectMake(X, Y, width, height);
    }];
    
    [self.hotArray removeAllObjects];
    [[HJCityManager manager] loadRequestWithSuccess:^(NSArray * _Nonnull dataArray) {
        [weakSelf.hotArray addObjectsFromArray:dataArray];
        [weakSelf.collectionView reloadData];
    }];
    [weakSelf.collectionView reloadData];
}

-(UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        layout.itemSize = CGSizeMake((SCREEN_WIDTH - 12 - 42 - 30 - 20) / 3, 35);
        layout.minimumLineSpacing = 15;
        layout.minimumInteritemSpacing = 0;
        layout.sectionInset = UIEdgeInsetsMake(0, 20, 0, 0);
        
        CGFloat width = SCREEN_WIDTH - 24 - 30;
        CGFloat height = SCREEN_HEIGTH - Height_NavBar - 5 - (IS_FULL_SCREEN ? 34 : 12);
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, width, height) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
//        _collectionView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerNib:[UINib nibWithNibName:@"HJCityCell" bundle:nil] forCellWithReuseIdentifier:identifier];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:Headridentifier];
        
        [self.collectionBG addSubview:_collectionView];
    }
    return _collectionView;
}
-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.tableBG.frame), self.tableBG.height) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = 20;
        _tableView.estimatedRowHeight = UITableViewAutomaticDimension;
        _tableView.backgroundColor = [UIColor clearColor];
        [_tableView registerCellByClassName:@"UITableViewCell"];
        [self.collectionBG addSubview:_tableView];
    }
    return _tableView;
}
#pragma mark -- UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return [self.dict allKeys].count+count;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return self.hotArray.count;
    }else {
        return [self.dict[self.dataArray[section-count]] count];
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HJCityCell * cityCell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    if (indexPath.section==0) {
        NSDictionary * hotDic = self.hotArray[indexPath.row];
        cityCell.cityLabel.text = hotDic[@"cityName"];
    }else {
        NSDictionary * dic = self.dict[self.dataArray[indexPath.section-count]][indexPath.row];
        cityCell.cityLabel.text = dic[@"cityName"];
    }
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
//    });
    return cityCell;
}
//- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
//    return UIEdgeInsetsMake(4, 20, 4, 20);
//}
// 自定义header
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView * reusbleView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:Headridentifier forIndexPath:indexPath];
        for (UIView * view in reusbleView.subviews) {
            [view removeFromSuperview];
        }
        UILabel * label = [[UILabel alloc]init];
        NSArray * array;
        array = [[NSMutableArray alloc]initWithObjects:@"热门城市", nil];
        array = [array arrayByAddingObjectsFromArray:[NSMutableArray arrayWithArray:self.dataArray]];
        label.text = array[indexPath.section];
        label.textColor = [UIColor colorWithHex:0x333333];
        label.font = [UIFont fontWithName:PingFangSC_Medium size:16];
        label.frame = CGRectMake(20, 6, collectionView.width-20, 30);
        label.textAlignment = NSTextAlignmentLeft;
        [reusbleView addSubview:label];
        
        return reusbleView;
    }
    return nil;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(collectionView.width-20, 35);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0) {
        if (self.cityBlock) {
            self.cityBlock(self.hotArray[indexPath.row]);
        }
    }else {
        if (self.cityBlock) {
            self.cityBlock(self.dict[self.dataArray[indexPath.section-count]][indexPath.row]);
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
}
//-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
//    NSLog(@"Desel=%d",indexPath.row);
//}
#pragma mark -- UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UILabel * label = [UILabel new];
    label.text = self.dataArray[indexPath.row];
    label.textColor = [UIColor colorWithHex:0x333333];
    label.font = [UIFont fontWithName:PingFangSC_Medium size:13];
    label.frame = CGRectMake(0, 0, 30, 20);
    label.textAlignment = NSTextAlignmentCenter;
    [cell.contentView addSubview:label];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSLog(@"%@",self.dataArray[indexPath.row]);
//    NSArray *sectionArray = self.dict[self.dataArray[indexPath.row]];
//    LKLog(@"当前Section的数组：%zd", sectionArray.count);
//    NSInteger row = sectionArray.count;
//    NSInteger row = [self.dict[self.dataArray[indexPath.row]] count];
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:indexPath.row] atScrollPosition:UICollectionViewScrollPositionTop animated:NO];
}

#pragma mark - 更新约束
- (void)updateViewConstraints {
    [super updateViewConstraints];
    self.tableViewBGConstraintBottom.constant = IS_FULL_SCREEN ? 0 : 12;
}

@end
